package cn.wang.utils;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ObjectOutput;
import java.util.Properties;

/**
 * Created by john on 2017/11/6.
 */
public class MailUtils {
/*
*发送邮件
* @param to 收件件地址
* @param object 主题
* @param  text 正文
*
* */

    public static void sendMail(String to, String subject, String text) {
        //配置文件
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.sina.com");
        props.put("main.smtp.auth", "true");
        //获取和smtp服务器的会话
        Session session = Session.getInstance(props);
        //构造信息体
        MimeMessage message = new MimeMessage(session);
        //发件地址
        try {
            Address address = new InternetAddress("15282723985@sina.cn");
            message.setFrom(address);
            //收件地址
            Address toaddress = new InternetAddress(to);
            message.setRecipient(MimeMessage.RecipientType.TO, toaddress);
            //主题
            message.setSubject(subject);
            //正文
           // message.setText(text);
            message.setContent(text,"text/html;charset=utf-8");
            message.saveChanges();
            //获取传输端口对象
            Transport transport = session.getTransport("smtp");
            //通过传输对象获取服务器
            transport.connect("smtp.sina.com", "15282723985@sina.cn", "1998123aini");
            //关闭端口
            //发送
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();

        }
    }
}
